package codeRandomThoughts.Test107二叉树的层序遍历II;

import codeRandomThoughts.utils.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        //层序遍历用队列实现
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> result = new ArrayList<>();
        if (root == null)
            return results;

        //记录每层节点个数
        int npl = 0; //number per level
        TreeNode node = root;
        queue.offer(node);
        while (!queue.isEmpty()) {
            npl = queue.size();
            while (npl > 0) {
                node = queue.poll();
                result.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                npl--;
            }
            results.add(0, result);
            result = new ArrayList<>();
        }
        return results;

    }
}
